<?php
require_once('./db.php');

/*********************************************************
** Function: auth()                                     **
**   Params: $username - Name of user to authenticate   **
**           $password - Passwd of user to authenticate **
**     Desc: Authenticates a given user. Involves a     **
**           check that the given username and passwd   **
**           exists in users table.                     **
*********************************************************/
function auth($username, $password) {
		
	$username = strtoupper(mysql_real_escape_string($username));
	$password = mysql_real_escape_string($password);
	
    $query = "SELECT username, userID FROM ".TABLE_PREFIX."_users WHERE UPPER(username) = '".$username."' AND password = '".$password."'";
	
	// Execute the query
    $result = mysql_query($query);
    
	// If we found a match...
    if (mysql_num_rows($result) == 1){
        $data = @mysql_fetch_object($result);
        //make an array for the username and userID
		$boardUser = array('username' => stripslashes($data->username), 'id' => $data->userID);
		
		//toss them in the online table
		setOnline($boardUser['username'], $boardUser['id']);
    }else{
        $boardUser = "";
    }

    return $boardUser;
}

function getUserID($username) {

	$username = strtoupper(mysql_real_escape_string($username));
	
	$result = mysql_query("SELECT userID FROM ".TABLE_PREFIX."_users WHERE UPPER(username) = '".$username."'");
	
	if(mysql_num_rows($result) > 0){
		$data = mysql_fetch_object($result);
		$userID = $data->userID;
	}else{
		$userID = 0;
	}
	
	return $userID;
}

function getUsername($userID) {
	//just return the string of the username based off the ID
	
	$result = mysql_query("SELECT username FROM ".TABLE_PREFIX."_users WHERE userID = ".mysql_real_escape_string($userID));
	if(!$result){
		return "BAD USER ID   ".$userID;
	}
	if(mysql_num_rows($result) > 0){
		$data = mysql_fetch_object($result);
		$username = $data->username;
	}else{
		$username = "";
	}
	
	return $username;
}

function handlePassword($rawPassword){
	return md5(mysql_real_escape_string($rawPassword));
}

function fail($errorToFlash) {
	echo "&errorMsg=".$errorToFlash;
}

//
// Function to check if the email address is well formed
//
function checkEmail($email){
    // Define regular expression
    $regexp = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";

    if (eregi($regexp, $email)){
    	return true;
    }else{
        return false;
    }
}

//
//get the users private messages
//
function privateMessages($userID, $privateMessageLimit){
	
	$limit = mysql_real_escape_string($privateMessageLimit);
	
	$query = "SELECT SQL_CALC_FOUND_ROWS recipientStatus FROM ".TABLE_PREFIX."_private 
			  WHERE recipientID = $userID 
			  AND recipientStatus != ".PM_DELETE_MESSAGE." 
			  AND recipientStatus != ".PM_TRASH_MESSAGE."
			  AND senderID != $userID 
			  ORDER BY sent DESC LIMIT $limit";
	$result = @mysql_query($query);
	
	$totalResult = mysql_query("SELECT FOUND_ROWS() AS privateTotal");
	$dataTotal = mysql_fetch_object($totalResult);
	$privateCount = $dataTotal->privateTotal;
	
	$newCount = 0;
	while($private = @mysql_fetch_object($result)){
		$privateNew = $private->recipientStatus;
		if($privateNew == PM_NEW_MESSAGE){
			$newCount++;
		}
	}
	// Output the status back to Flash
	return "&privateNew=$newCount&privateTotal=$privateCount";
}

function setOnline($username, $userID){
	//take the username and ID and toss them in the database
	$result = mysql_query("REPLACE INTO ".TABLE_PREFIX."_online (userID, username, lastUpdate) VALUES ($userID, '$username', ".time().")");
	$result = mysql_query("UPDATE ".TABLE_PREFIX."_users SET lastOnline = ".time()." WHERE userID = ".$userID);
}

function viewOnline($timeoutInSeconds, $currentRecord, $dateFormat){
	//list all the people that are online within the last $timeout
	$timeLimit = time() - mysql_real_escape_string($timeoutInSeconds);
	
	$result = mysql_query("SELECT * FROM ".TABLE_PREFIX."_online");
	
	$onlineUsers = "";
	$totalOnline = 0;
	
	//loop through the results and delete the old ones
	while($data = mysql_fetch_object($result)){
		$username = stripslashes($data->username);
		$userID = $data->userID;
		$lastUpdate = $data->lastUpdate;
		
		if($lastUpdate > $timeLimit){
			//output it to flash in the form of userID|username
			$onlineUsers .= $userID."|".$username.",";
			$totalOnline++;
		}else{
			//delete it from the table
			$delete = mysql_query("DELETE FROM ".TABLE_PREFIX."_online WHERE userID = $userID");
		}
	}
	
	//see if we broke a record
	$recordUsers = explode(",", $currentRecord);
	
	if($totalOnline > $recordUsers[0]){
		//update the database with the new values
		$result = mysql_query("UPDATE ".TABLE_PREFIX."_config SET configValue = '".$totalOnline.",".time()."' WHERE configName = 'MOST_ONLINE_USERS'");
		
		$recordUsers[0] = $totalOnline;
		$recordUsers[1] = time();
	}
	
	//remove the trailing comma
	$onlineUsers = "&onlineUsers=".substr($onlineUsers, 0, strlen($onlineUsers) - 1);
	
	//deliver the record
	$record = "&recordUsers=".$recordUsers[0]."&recordTime=".strftime($dateFormat, $recordUsers[1]);
	
	return $onlineUsers.$record;
}

//sends an e-mail
function sendMail($to, $subject, $message, $boardName, $boardEmail){
	@mail(stripslashes($to), stripslashes($subject), stripslashes($message), stripslashes("From: ".$boardName."<".$boardEmail.">\r\n" . "Reply-To: ".$boardName."<".$boardEmail.">\r\n"));
}

function trackThread($userID, $forumID, $threadID, $lastPostViewed){
	//this will take a thread the user has viewed and tag it in the db
	$userID = mysql_real_escape_string($userID);
	$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_threadtrack (userID, forumID, threadID, lastPostViewed) VALUES ($userID, $forumID, $threadID, $lastPostViewed) ON DUPLICATE KEY UPDATE lastPostViewed = $lastPostViewed");
}

function newPostsInForum($userID, $forumID, $maxTime){
	$userID = $userID;
	$maxTime = mysql_real_escape_string($maxTime);
	
	$result = mysql_query("SELECT threadID, lastPost
						  	FROM ".TABLE_PREFIX."_threads
							WHERE forumID = $forumID
							AND lastPost > $maxTime
							ORDER BY lastPost ASC");
	
	//loop through the results and see if we are tracking any of them, if we aren't then we have a new post
	while($data = mysql_fetch_object($result)){
		
		$resultTrack = mysql_query("SELECT lastPostViewed
								   	FROM ".TABLE_PREFIX."_threadtrack
									WHERE userID = $userID
									AND threadID = ".$data->threadID);
		
		if(mysql_num_rows($resultTrack) > 0){
			//if we have it in the database, see if the posts are newer
			$dataTrack = mysql_fetch_object($resultTrack);
			
			//let's see if we have a new post
			if($dataTrack->lastPostViewed < $data->lastPost){
				//new post!
				return $dataTrack->lastPostViewed;
			}
		}else{
			//no rows means new posts!
			return $data->threadID;
		}
	}
	
	//if we made it this far then there isn't any new posts
	return -1;
}

function newPostsInThread($userID, $threadID){
	
	$userID = mysql_real_escape_string($userID);
	//hit the track database for this thread and return the first post time AFTER the last time we were there
	$result = mysql_query("SELECT lastPostViewed
							FROM ".TABLE_PREFIX."_threadtrack
							WHERE threadID = $threadID
							AND userID = $userID");
	if(mysql_num_rows($result) > 0){
		$data = mysql_fetch_object($result);
		return $data->lastPostViewed;
	}else{
		return 0;
	}
}

function timeParse($unix_timestamp, $dynamic_days = false){
	if($unix_timestamp != 0){
		//default output
		$date = strftime("%m/%d/%Y %H:%M", $unix_timestamp);
		
		//single day in seconds
		$day = 86400;
		
		if($dynamic_days){
			//this allows an output to be a bit more dynamic
			if($unix_timestamp > time() - $day){
				//just show the time of day since it's still the same day
				$date = strftime("%I:%M %p", $unix_timestamp);
			}elseif($unix_timestamp > time() - ($day * 365)){
				//show the month and day since it's the same year
				$date = strftime("%b. %d", $unix_timestamp);
			}else{
				//otherwise just return a month day, year sort of deal	
				$date = strftime("%b. %d, %Y", $unix_timestamp);
			}
		}
		
		return $date;
	}else{
		return $unix_timestamp;
	}
}

//text parser which takes text to be parsed, parses it and shoots it back to flash
function textParse($text) {
	/*  uncomment if you don't want people to swear
	// Swear Word Filtering Section
	$badwords = Array ("fuck", "shit", "bastard", "fucker", "fucking", "damn", "bitch");
	$changeto = '****';
	$text = str_replace ($badwords, $changeto, $text);
	*/
	//if the user doesn't put http:// before the www.
	$text = str_replace("www.", "http://www.", $text);
	
	// BOLD, ITALICS, UNDERLINE AND PRE PARSER - http://http:// fix as well
	$searchFor = Array('[b]', '[/b]', '[pre]', '[/pre]', '[i]', '[/i]', '[u]', '[/u]', '\r', '\n', '&amp;', 'http://http://', 'ftp://http://', 'https://http://');
	$replaceWith = Array('<b>', '</b>', '<pre>', '</pre>', '<i>', '</i>', '<u>', '</u>', '<br>', '<br>', '&', 'http://', 'ftp://', 'https://');
	$text = str_replace($searchFor, $replaceWith, $text);
	
	// search for the []'s and replace with what you need to replace!
	$searchTag = array();
	$replaceTag = array();
	
	// parse [url] tags
	$searchTag[0] = "#\[url\]([a-z]+?://){1}(.*?)\[/url\]#si";
	$replaceTag[0] = '<font color="#2667A8"><u><a href="\1\2" target="_blank">\1\2</A></u></font>';
	
	// parse the [url] tags without the http:// there
	$searchTag[1] = "#\[url\](.*?)\[/url\]#si";
	$replaceTag[1] = '<font color="#2667A8"><u><a href="http://\1" target="_blank">\1</A></u></font>';
	
	// parse the [url=whatver] tags 
	$searchTag[2] = "#\[url=([a-z]+?://){1}(.*?)\](.*?)\[/url\]#si";
	$replaceTag[2] = '<font color="#2667A8"><u><a href="\1\2" target="_blank">\3</A></u></font>';
	
	// parse [url= www.whatever] if there is no http://
	$searchTag[3] = "#\[url=(.*?)\](.*?)\[/url\]#si";
	$replaceTag[3] = '<font color="#2667A8"><u><a href="http://\1" target="_blank">\2</A></u></font>';
	
	//parse inline e-mail addresses
	$searchTag[4] = "/([\w\.]+)(@)([\S\.]+)\b/i";
	$replaceTag[4] = '<font color="#2667A8"><u><a href="mailto:$0">$0</a></u></font>';
	
	//parse the [quote] tags
	$searchTag[5] = "#\[quote\](.*?)\[/quote\]#si";
	$replaceTag[5] = '<br><font color="#999999">___ <i>quote:</i> __________________________________________________________________________<br><b>\1</b><br>___________________________________________________________________________________<br></font>';
	
	$text = preg_replace($searchTag, $replaceTag, $text);
	
	// Parse: inline URLs
    $text = eregi_replace("(^|[^\">])((http|ftp|https)://([a-z0-9/?#&+._=-]*))([^\">]|$)", "\\1<font color=\"#2667A8\"><u><a href=\"\\2\" target=\"_blank\">\\2</a></u></font>\\5", $text);

	// Parse DirectLink URLs - Edit for your own site
    //$newInstallDirectory = str_replace(".", "\.", $installDirectory);
	//$text = eregi_replace("\"$newInstallDirectory"."gothread\.php\?threadID=([0-9]*)\" target=\"_blank\"", "\"asfunction:mainLevel.board.getPosts,\\1\"", $text);
	//$text = eregi_replace("\"http://www\.mxprojects\.com/gothread\.php\?threadID=([0-9]*)\" target=\"_blank\"", "\"asfunction:mainLevel.board.getPosts,\\1\"", $text);

	return $text;
}

function checkAdminPermissions($userID) {
	//groupID 4 is reserved for global admins
	$adminGroup = 4;
	
	$result = mysql_query("SELECT gm.userID FROM ".TABLE_PREFIX."_groupmembers gm WHERE gm.groupID = $adminGroup AND gm.userID = ".$userID);
	
	if(mysql_num_rows($result) > 0){
		return 1;
	}else{
		return 0;
	}
}

function checkForumPermissions($forumID, $userID, $guestGroupID){
	//this will make sure that when a user checks threads or posts that they are allowed to be there
	$query = "SELECT f.groupID";
	
	//see if they are a guest or not
	if($userID == -1){
		//this means they are a guest
		$query .= " FROM ".TABLE_PREFIX."_forums f WHERE f.forumID = ".$forumID." AND f.groupID = ".$guestGroupID;
	}else{
		//they are a member
		$query .= ", gm.isAdmin, gm.isModerator, gm.isAllowedToPost FROM ".TABLE_PREFIX."_forums f, ".TABLE_PREFIX."_groupmembers gm 
				WHERE f.forumID = ".$forumID." 
				AND gm.userID = ".$userID." 
				AND f.groupID IN (".$guestGroupID.", gm.groupID)
				GROUP BY gm.userID";		
	}	
	
	//run the query
	$result = mysql_query($query);
	
	//if no results returned then they don't have access
	if(mysql_num_rows($result) == 0){
		return false;
	}else{
		//if they are gtg, fire them off the perms
		$data = mysql_fetch_object($result);
		
		//set the default array as if they were a guest
		$perms = "&isAdmin=0&isModerator=0&isAllowedToPost=0";

		//see if it's a guest or a user
		if(isset($data->isAllowedToPost)){
			//this means they are a member. set up the perms.	
			$perms = "&isAdmin=".$data->isAdmin."&isModerator=".$data->isModerator."&isAllowedToPost=".$data->isAllowedToPost;
		}
		
		//send the perms back to the script
		return $perms;
	}
}
?>